<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { postWorkflowData } from '@/api/examples'
import { useUserStore } from '@/store/user'
// import SytPreviewItem from '@/components/SytEditForm/SytPreviewItem.vue'

const userStore = useUserStore()

const props = defineProps({
  data: {
    type: Object,
    default() {
      return {
        name: '',
        formData: [],
        flowData: {
          nodesData: [],
          linesData: []
        }
      }
    }
  }
})

const emit = defineEmits(['submit'])

let workflowData = ref({
  name: '',
  formData: [],
  flowData: {
    nodesData: [],
    linesData: []
  }
})
watch(
  () => JSON.parse(JSON.stringify(props.data)),
  (data) => {
    workflowData.value = data
  },
  {
    deep: true,
    immediate: true //解决第一次打开组件watch不起作用的问题
  }
)
//根据field获取formTemplateData的项
const getFormItemByField = (field) => {
  for (let item of workflowData.value.formData) {
    if (item.type === 'layout') {
      for (let v of item.cols) {
        for (let element of v.children) {
          if (field === element.field) return element
        }
      }
    } else if (field === item.field) return item
  }
}
//时间线数据
let timeLineData = computed(() => {
  return handleFlowData(workflowData.value)
})
//部门主管
let director = ref({
  label: '部门主管',
  value: '部门主管'
})
// getDepartmentPersonnel().then((res) => {
//   director.value = res.data
//     .find((v) => v.value == userStore.department)
//     ?.children.find((v) => v.label.includes('主管'))
// })
//根据条件生成流程数据
const handleFlowData = (workflowData) => {
  let resultArr = []
  let fromNode: any = { id: '', type: '' }
  let { nodesData, linesData } = workflowData.flowData

  let startNode = (fromNode = nodesData.find((v) => v.type === 'start'))
  if (!startNode) return []
  startNode.color = '#00aabb'
  resultArr.push(startNode)

  while (linesData.find((v) => v.fromId === fromNode.id)) {
    let toNode: any = { id: '' }
    let lines: any[] = linesData.filter((v) => v.fromId === fromNode.id)
    if (fromNode.type == 'condition') {
      //条件块
      let yesIndex = lines.findIndex((v) => v.text === '是')
      let noIndex = lines.findIndex((v) => v.text === '否')
      let index = yesIndex
      let { field, comparison, value } = fromNode.properties
      let item = getFormItemByField(field)

      if (item) {
        switch (comparison) {
          case '小于':
            item.value < value ? (index = yesIndex) : (index = noIndex)
            break
          case '等于':
            item.value === value ? (index = yesIndex) : (index = noIndex)
            break
          case '大于':
            item.value > value ? (index = yesIndex) : (index = noIndex)
            break
        }
      }

      toNode = nodesData.find((v) => v.id === lines[index]?.toId)
    } else {
      toNode = nodesData.find((v) => v.id === lines[0]?.toId)

      if (toNode?.type == 'handle') {
        if (toNode.properties?.value == '部门主管') toNode.properties = director.value
      }
    }
    if (toNode?.type != 'condition') resultArr.push(toNode)

    fromNode = toNode
  }

  return resultArr
}

const ruleFormRef = ref()

const workflowDataToFormData = () => {
  let postData = new FormData()
  postData.append('name', workflowData.value.name)
  postData.append(
    'submitter',
    JSON.stringify({
      username: userStore.username,
      nickname: userStore.nickname
    })
  )

  let formData = {}
  workflowData.value.formData.forEach((item) => {
    if (item.type === 'img-upload') {
      //midway upload组件只支持文件的field重名
      item.value.forEach((v) => postData.append(item.field, v))
    } else {
      if (item.type === 'layout') {
        item.cols.forEach((v) => {
          v.children.forEach((element) => {
            if (element.type === 'img-upload') {
              element.value.forEach((v) => postData.append(element.field, v))
            } else formData[element.field] = element.value
          })
        })
      } else formData[item.field] = item.value
    }
  })
  postData.append('formData', JSON.stringify(formData))

  let flowData = timeLineData.value
    .filter((v) => v.type === 'handle')
    .map((v) => ({
      id: v.id,
      type: v.text,
      label: v.properties.label,
      username: v.properties.value,
      status: '未处理'
    }))
  postData.append('flowData', JSON.stringify(flowData))

  return postData
}

const submitForm = (formEl) => {
  if (!formEl) return false
  formEl.validate((valid) => {
    if (valid) {
      postWorkflowData(workflowDataToFormData()).then(() => emit('submit'))
    } else {
      return false
    }
  })
}
</script>

<template>
  <el-space direction="vertical" fill class="submit-container">
    <el-card>
      <template #header>
        <h1>{{ workflowData.name }}</h1>
      </template>
      <!-- <el-form ref="ruleFormRef" :model="workflowData.formData">
        <SytPreviewItem
          v-for="(item, index) of workflowData.formData"
          :key="item.field"
          v-model="workflowData.formData[index]"
          :index="index.toString()"
          :rule-form-ref="ruleFormRef"
          @cascader-fetch="item.options = $event"
        />
      </el-form> -->
    </el-card>
    <el-card>
      <template #header>
        <span>流程</span>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="activity of timeLineData"
          :key="activity.id"
          :icon="activity.icon"
          :color="activity.color"
          :timestamp="activity.timestamp"
        >
          <div>{{ activity.text }}</div>
          <div>{{ activity.properties?.label }}</div>
        </el-timeline-item>
      </el-timeline>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
    </el-card>
  </el-space>
</template>

<style scoped>
.submit-container {
  display: block;
  width: 70%;
  margin: 0 auto;
}
@media screen and (max-width: 500px) {
  .submit-container {
    width: 100%;
  }
}
</style>
@/api/examples
